﻿using System;
using System.Collections.Generic;
using System.Configuration;
using Backend.JYD.Messages.Exceptions;

namespace Backend.JYD.Config
{
    public class AppConfigs<T> where T : BaseConfig
    {
        #region properties

        private Dictionary<string, T> _Configs = null;

        private static AppConfigs<T> _AppConfigs = null;
        public static AppConfigs<T> Instance
        {
            get
            {
                if (_AppConfigs == null)
                {
                    _AppConfigs = new AppConfigs<T>();
                    T config = Activator.CreateInstance<T>();
                    _AppConfigs.InitConfigs(config.SectionName);
                }
                return _AppConfigs;
            }
        }

        #endregion

        #region constract/destract

        private AppConfigs()
        {
            _Configs = new Dictionary<string, T>();
        }

        #endregion

        #region Init
        public static void Reset()
        {
            _AppConfigs = null;
        }

        private void InitConfigs(string configname)
        {
            ConfigurationManager.GetSection(configname);
            if (_Configs == null)
            {
                throw new ConfigMessageException(Messages.Manager.ConfigMessages.Messages.CannotFindTheSectionName, configname);
            }
        }

        #endregion

        #region method

        internal void AddConfig(T config)
        {
            if (_Configs.ContainsKey(config.Name))
                throw new ConfigMessageException(Messages.Manager.ConfigMessages.Messages.TheSectionExistMoreThenOneConfig, config.SectionName, config.Name);
            _Configs.Add(config.Name, config);
        }

        public T GetConfig(string name)
        {
            if (_Configs.ContainsKey(name))
            {
                return _Configs[name] as T;
            }
            return default(T);
        }

        public Dictionary<string, T> Configs
        {
            get { return _Configs; }
        }

        #endregion
    }
}
